package local_oss

import (
	"config-client-v1/init/global"
	"config-client-v1/utils/tools"
	"errors"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"
)

type Response struct {
	Code    int
	Message string
	Data    string
}

var AllowDir = map[string]bool{
	"tmp":    true,
	"upload": true,
}

func CheckPathPermission(path string) bool {
	prefixLinux := strings.Split(path, "/")[0]
	prefixWindows := strings.Split(path, "\\")[0]
	if !AllowDir[prefixLinux] && !AllowDir[prefixWindows] {
		return false
	}
	return true
}

// ObjectExist 文件是否存在
func ObjectExist(key string) (exist bool, err error) {
	if key == "" {
		err = errors.New("key cant be empty")
		return
	}
	if CheckPathPermission(key) == false {
		err = errors.New("permission denied")
		return
	}
	sourcePath := path.Join(global.StaticPath, key)
	exist, err = tools.FileExist(sourcePath)
	return
}

func ObjectDelete(key string) (err error) {
	if key == "" {
		err = errors.New("key cant be empty")
		return
	}
	if CheckPathPermission(key) == false {
		err = errors.New("permission denied")
		return
	}
	sourcePath := path.Join(global.StaticPath, key)
	//fmt.Println("删除文件 sourcePath", sourcePath)
	err = os.Remove(sourcePath)
	return
}

func ObjectMove(key string, destPath string) (newPath string, err error) {
	if key == "" {
		err = errors.New("key cant be empty")
		return
	}
	if CheckPathPermission(key) == false {
		err = errors.New("permission denied key")
		return
	}
	if CheckPathPermission(destPath) == false {
		err = errors.New("permission denied destPath")
		return
	}
	sourcePath := path.Join(global.StaticPath, key)
	dstObject := path.Join(global.StaticPath, destPath, filepath.Base(sourcePath))
	if sourcePath == destPath {
		return sourcePath, nil
	}
	exist, err := tools.FileExist(sourcePath)
	if err != nil {
		return
	}
	if !exist {
		err = errors.New("key not found")
		return
	}
	tools.CreateDir(filepath.Dir(dstObject))
	newPath = path.Join(destPath, filepath.Base(sourcePath))
	err = os.Rename(sourcePath, dstObject)
	return
}

func DeleteOldPics(oldArr []string, newArr []string) {
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println("DeleteOldPics: ", err)
		}
	}()
	for _, v1 := range oldArr {
		inArray := false
		for _, v2 := range newArr {
			if v1 == v2 {
				inArray = true
				break
			}
		}
		if inArray == false {
			go ObjectDelete(v1)
		}
	}
}
